package com.ys.comparatordemo;

/**
 * 描述: 根据学生的年龄进行排序
 *     一个 规则类
 *
 * @author CodeYang
 * @version 2020/12/18 20:46
 */
public class OrderByAgeAsc implements Comparator,java.util.Comparator{
    /**
     *  升序排序 根据 年龄
     * @param object1
     * @param object2
     * @return
     *    a == b = 0
     *    a > b  = 1
     *    a < b  = -1
     */
    @Override
    public int compare(Object object1, Object object2) {
        // 1向下转型
        if (object1 instanceof Student && object2 instanceof Student){
            Student stu1 = (Student) object1;
            Student stu2 = (Student) object2;
            double flag = stu1.getAge()- stu2.getAge();
            // 降序排序
            return flag == 0 ? 0 : flag > 0 ? 1 : -1 ;
        }
        // 执行到此处，证明obj1或obj2不是Student类型的实例
        throw new IllegalArgumentException("obj1或obj2不是Student类的实例！");
    }
}
